﻿using AutoMapper;
using DFGK.WMS.Common;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.NoNet;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.IdentityModel.Logging;
using NetTaste;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace DFGK_WMS.Repository
{
    public class TCellRepository : BaseRepository<TCell>, ITCellRepository
    {

        private readonly SqliteContext sqlite;
        public TCellRepository(DFGK_DB context, IMapper mapper, SqliteContext sqlite) : base(context, mapper)
        {
            this.sqlite = sqlite;
        }

        /// <summary>
        /// 仓位左侧树形显示
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Menuitem> GetMenuitem()
        {
            var wlist = Context.TWarehouses.AsNoTracking().ToList();

            return wlist.Select(item => new Menuitem
            {
                label = item.Name,
                value = item.Id,
                icon = item.Code,
                alias = "wh",
            }).ToList();
        }


        public List<Menuitem> GetShelfMenuitem(int aid)
        {
            var list = Context.TShelves;
            return list.Select(x => new Menuitem
            {
                label = x.Name,
                value = x.Id,
                icon = x.Code,
                alias = "shelf",
                children = null
            }).ToList();
        }

        /// <summary>
        /// 添加仓位
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTcell(TCell obj, out string message)
        {
            message = "";
            try
            {
                var cobj = Context.TCells.AsNoTracking().FirstOrDefault(x => x.Code == obj.Code);
                if (cobj != null)
                {
                    message = "编码已存在！";
                    return false;
                }
                //库房
                var wobj = Context.TWarehouses.Find(obj.WhId);
                if (wobj != null && wobj.Status == 1)
                {
                    obj.WhName = wobj.Name;
                    obj.WhCode = wobj.Code;
                }
                else
                {
                    message = "库房不存在或已被禁用！";
                    return false;
                }
                //货架
                var sobj = Context.TShelves.Find(obj.ShelfId);
                if (sobj != null && sobj.Status == 1)
                {
                    obj.ShelfCode = sobj.Code;
                    obj.ShelfName = sobj.Name;
                }
                else
                {
                    message = "货架不存在或已被禁用！";
                    return false;
                }

                obj.DistanceValue = Convert.ToDecimal(Math.Sqrt(Math.Pow(obj.LayerNo, 2) + Math.Pow(obj.ColumnNo, 2) + Math.Pow(obj.LineNo - 1, 2)));
                int lineNO = 0;
                int layerNO = obj.LayerNo;
                int columnNO = obj.ColumnNo;
                if (obj.LineNo < 7)
                {
                    lineNO = obj.LineNo;
                }
                else
                {
                    lineNO = obj.LineNo + obj.DepthIndex + (obj.LineNo - 7);
                }
                obj.Erpcode = lineNO.ToString("00") + layerNO.ToString("00") + columnNO.ToString("00");
                obj.CreateDate = DateTime.Now;
                Context.TCells.Add(obj);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 修改仓位
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateTcell(TCell obj, out string message)
        {
            message = "";
            try
            {
                var cobj = Context.TCells.AsNoTracking().FirstOrDefault(x => x.Id != obj.Id && x.Code == obj.Code);
                if (cobj != null)
                {
                    message = "编码已存在！";
                    return false;
                }
                //库房
                var wobj = Context.TWarehouses.Find(obj.WhId);
                if (wobj != null && wobj.Status == 1)
                {
                    obj.WhName = wobj.Name;
                    obj.WhCode = wobj.Code;
                }
                else
                {
                    message = "库房不存在或已被禁用！";
                    return false;
                }
                //货架
                var sobj = Context.TShelves.Find(obj.ShelfId);
                if (sobj != null && sobj.Status == 1)
                {
                    obj.ShelfCode = sobj.Code;
                    obj.ShelfName = sobj.Name;
                }
                else
                {
                    message = "货架不存在或已被禁用！";
                    return false;
                }
                obj.DistanceValue = Convert.ToDecimal(Math.Sqrt(Math.Pow(obj.LayerNo, 2) + Math.Pow(obj.ColumnNo, 2) + Math.Pow(obj.LineNo - 1, 2)));
                int lineNO = 0;
                int layerNO = obj.LayerNo;
                int columnNO = obj.ColumnNo;
                if (obj.LineNo < 7)
                {
                    lineNO = obj.LineNo;
                }
                else
                {
                    lineNO = obj.LineNo + obj.DepthIndex + (obj.LineNo - 7);
                }
                obj.Erpcode = lineNO.ToString("00") + layerNO.ToString("00") + columnNO.ToString("00");
                obj.ModifyDate = DateTime.Now;
                Context.TCells.Update(obj);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool DelTcell(int uid)
        {
            try
            {
                var del = Context.TCells.Find(uid);
                if (del != null)
                {
                    Context.TCells.Remove(del);
                    return Context.SaveChanges() > 0;
                }
                return false;
            }
            catch (Exception)
            {
                throw;
            }
        }

        // <summary>
        /// 获取库房(仓库)信息
        /// </summary>
        /// <returns></returns>
        public List<TWarehouse> GetTwarehouseList()
        {
            try
            {
                return Context.TWarehouses.ToList();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 根据id获取数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public TCell GetTcellById(int id)
        {
            try
            {
                return Context.TCells.Find(id);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 批量设置
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool UpdateSetUp(Tcellll obj)
        {
            using (var trans = Context.Database.BeginTransaction())
            {
                try
                {
                    if (obj.Id == null)
                    {
                        return false;
                    }
                    foreach (var item in obj.Id)
                    {
                        var res = Context.TCells.AsNoTracking().FirstOrDefault(p => p.Id == item);
                        if (res is null)
                        {
                            return false;
                        }
                        res.LogicalPartCode = obj.LogicalPartCode;
                        res.LogicalPartName = obj.LogicalPartName;
                        Context.TCells.Update(res);
                        Context.SaveChanges();

                    }
                    Context.SaveChanges();
                    trans.Commit();
                    return true;
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }

        }

        /// <summary>
        /// 递归显示库房库区货架
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Menuitem> GetWarAreaShellList()
        {
            var wlist = Context.TWarehouses.AsQueryable();

            return GetWarAreaShellList(wlist.ToList());
        }

        /// <summary>
        /// 库房
        /// </summary>
        /// <param name="wlist"></param>
        /// <returns></returns>
        public List<Menuitem> GetWarAreaShellList(List<TWarehouse> wlist)
        {
            //var alist=Context.TAreas.AsQueryable();
            //var slist=Context.TShelves.AsQueryable();
            return wlist.Select(x => new Menuitem
            {
                value = x.Id,
                label = x.Name,
                alias = "wh",
            }).ToList();
        }

        /// <summary>
        /// 货架
        /// </summary>
        /// <param name="wid"></param>
        /// <returns></returns>
        public List<Menuitem> GetWarAreaShellList(string acode)
        {
            var slist = Context.TShelves.ToList();//.Where(x => x.AreaCode == acode).ToList();
            return slist.Select(x => new Menuitem
            {
                value = x.Id,
                label = x.Name,
                alias = "shelf",
                children = null
            }).ToList();
        }

        /// <summary>
        /// 列表显示
        /// </summary>
        /// <param name="logicalPartCode"></param>
        /// <param name="fullStatus"></param>
        /// <param name="status"></param>
        /// <param name="cname"></param>
        /// <param name="whid"></param>
        /// <param name="areid"></param>
        /// <param name="sheid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<TCell> GetCellList(string logicalPartCode, int fullStatus, int status, string cname, int whid, int areid, int sheid, int pageIndex, int pageSize, out int totalCount)
        {
            var clist = Context.TCells.AsQueryable().ToList();
            //逻辑分区
            if (!string.IsNullOrEmpty(logicalPartCode))
            {
                clist = clist.Where(x => x.LogicalPartCode == logicalPartCode).ToList();
            }
            //仓位状态
            if (fullStatus < 3)
            {
                clist = clist.Where(x => x.FullStatus == fullStatus).ToList();
            }
            //状态
            if (status < 8)
            {
                clist = clist.Where(x => x.Status == status).ToList();
            }
            //仓位名称
            if (!string.IsNullOrEmpty(cname))
            {
                clist = clist.Where(x => x.Name.Contains(cname)).ToList();
            }
            //库房
            if (whid != 0)
            {
                clist = clist.Where(x => x.WhId == whid).ToList();
            }
            //货架
            if (sheid != 0)
            {
                clist = clist.Where(x => x.ShelfId == sheid).ToList();
            }
            totalCount = clist.Count();
            return clist.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 获取全部仓位
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TCell> GetAllCellList()
        {
            try
            {
                return Context.TCells.AsQueryable().ToList();
            }
            catch (Exception)
            {
                throw;
            }
        }

        public List<TPriceTags> GetAllPriceCellList()
        {
            return Context.TPriceTags.AsQueryable().ToList();
        }

        /// <summary>
        /// 批量添加仓位
        /// </summary>
        /// <param name="cellCreateBodyDTO"></param>
        /// <returns></returns>
        public bool BatchCreateCell(CellCreateBodyDTO cellCreateBodyDTO, out string message)
        {
            message = "";
            var dictItem = Context.TDictItems.AsNoTracking().Where(d => d.Id == cellCreateBodyDTO.CellTypeId).FirstOrDefault();
            if (dictItem == null)
            {
                message = "仓位类型不存在";
                return false;
            }
            List<TCell> cellList = new List<TCell>();
            var warehouse = Context.TWarehouses.AsNoTracking().Where(w => w.Id == cellCreateBodyDTO.WhId && w.Status == 1).FirstOrDefault();
            if (warehouse == null)
            {
                message = "库房不存在";
                return false;
            }
            List<TShelf> shelves = Context.TShelves.AsNoTracking().Where(s => s.WhId == cellCreateBodyDTO.WhId && /*s.AreaId == cellCreateBodyDTO.AreaId &&*/ s.Status == 1 && cellCreateBodyDTO.ShelfIds.Contains(s.Id)).ToList();
            if (shelves == null || shelves.Count == 0)
            {
                message = "货架不存在";
                return false;
            }
            //逻辑分区
            var defaultLogicPart = Context.TDictItems.AsNoTracking().Where(d => d.IsDefault == true && d.TypeCode == "LogicPartCode").FirstOrDefault();
            foreach (var shelf in shelves)
            {
                int lineNO = shelf.Number.GetValueOrDefault();
                if (lineNO <= 0)
                {
                    message = shelf.Name + "排号不正确";
                    return false;
                }
                int maxDepth = shelf.Depth.GetValueOrDefault();
                for (int layerIndex = 1; layerIndex <= cellCreateBodyDTO.MaxLayer; layerIndex++)
                {
                    for (int columnIndex = 1; columnIndex <= cellCreateBodyDTO.MaxColumn; columnIndex++)
                    {
                        for (int depthIndex = 0; depthIndex < maxDepth; depthIndex++)
                        {
                            bool isMaxDepth = depthIndex == maxDepth - 1;
                            var depthName = depthIndex == 0 ? "" :
                                                    depthIndex == 1 ? "2深位" :
                                                    depthIndex == 2 ? "3深位" :
                                                    depthIndex == 3 ? " 4深位" :
                                                    depthIndex == 4 ? "5深位" : "未知";
                            string name = string.Format("{0}排{1}层{2}列{3}", lineNO.ToString(), layerIndex.ToString(), columnIndex.ToString(), depthName);
                            string cellCode = string.Format("Cell:{0}_{1}_{2}_{3}", lineNO.ToString(), layerIndex.ToString(), columnIndex.ToString(), depthIndex.ToString());
                            int erpLineNO = lineNO;
                            string erpCode = erpLineNO.ToString("00") + layerIndex.ToString("00") + columnIndex.ToString("00") + depthIndex.ToString("00");
                            int heightType = (int)EmHeightType.H2300;
                            if (layerIndex == 1 || layerIndex == 2)
                            {
                                heightType = (int)EmHeightType.H2300;
                            }
                            else if (layerIndex == 3)
                            {
                                heightType = (int)EmHeightType.H1600;
                            }
                            else
                            {
                                heightType = (int)EmHeightType.H1150;
                            }
                            TCell cell = new TCell
                            {
                                Code = cellCode,
                                Name = name,
                                WhId = warehouse.Id,
                                WhName = warehouse.Name,
                                LineNo = lineNO,
                                LayerNo = layerIndex,
                                ColumnNo = columnIndex,
                                DepthIndex = depthIndex,
                                IsLock = false,
                                Status = (int)EmCellStatus.Normal,
                                IsMaxDepth = isMaxDepth,
                                FullStatus = 0,
                                BusinessType = 0,
                                CreateDate = DateTime.Now,
                                ShelfId = shelf.Id,
                                ShelfCode = shelf.Code,
                                ShelfName = shelf.Name,
                                CellType = (int)EmCellType.Normal,
                                Erpcode = erpCode,
                                DistanceValue = Convert.ToDecimal(Math.Sqrt(Math.Pow(layerIndex, 2) + Math.Pow(columnIndex, 2) + Math.Pow(lineNO - 1, 2))),
                                LogicalPartCode = defaultLogicPart == null ? "" : defaultLogicPart.ItemCode,
                                LogicalPartName = defaultLogicPart == null ? "" : defaultLogicPart.ItemName,
                                HeightType = heightType,
                                WhCode = warehouse.Code,
                            };
                            cellList.Add(cell);
                        }
                    }
                }
            }
            if (cellList == null || cellList.Count == 0)
            {
                return false;
            }
            bool result = false;
            using (var trans = Context.Database.BeginTransaction())
            {
                try
                {
                    foreach (var cell in cellList)
                    {
                        var count = Context.TCells.AsNoTracking().Where(c => c.WhId == warehouse.Id && c.ShelfId == cell.ShelfId && c.Code == cell.Code).Count();
                        if (count > 0)
                        {
                            continue;
                        }
                        Context.TCells.Add(cell);
                        Context.SaveChanges();
                    }
                    foreach (var shelf in shelves)
                    {
                        int cellCount = Context.TCells.AsNoTracking().Where(c => c.ShelfId == shelf.Id && c.Status == (int)EmCellStatus.Normal).Count();
                        int disabledCellCount = Context.TCells.AsNoTracking().Where(c => c.ShelfId == shelf.Id && c.Status == 0).Count();
                        shelf.CellCount = cellCount;
                        shelf.DisabledCellCount = disabledCellCount;
                        Context.TShelves.Update(shelf);
                        Context.SaveChanges();
                    }
                    Context.SaveChanges();
                    trans.Commit();
                    return true;
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }


        public TCell AllocateCell(int materialKeyId, int? qualityState, int heightType, out string errorMsg, string logicalPartCode = "")
        {
            errorMsg = "";
            TCell allotCell = null;
            try
            {
                TDictItem commonlogicalPartType = Context.TDictItems.AsNoTracking().Where(t => t.TypeCode == "LogicPartType" && t.ItemCode == "Common").FirstOrDefault();
                bool hasCell = false;
                int waitIndex = 0;
                string lineOrder = "ASC";
                do
                {
                    var cellQuery = Context.TCells.AsNoTracking().ToList(); //获取所以仓位
                    var inventoryQuery = Context.TInventory.AsNoTracking().ToList(); //获取库存数据
                    var shelves = Context.TShelves.AsNoTracking().ToList();

                    //cellQuery = cellQuery.Where(zw => zw.WhId == srcStation.WhId).ToList();
                    //inventoryQuery = inventoryQuery.Where(zw => zw.WarehouseId == srcStation.WhId).ToList();
                    //shelves = shelves.Where(s => s.WhId == srcStation.WhId).ToList();


                    var shelvesList = shelves.Where(s => s.Status == 1).ToList();
                    if (!string.IsNullOrEmpty(logicalPartCode) && shelvesList != null && shelvesList.Count > 0)
                    {
                        //List<int> enabledShelves = shelvesList.Select(t => t.Id).ToList();//只取巷道id
                        //List<int> routewayIds = cellQuery.Where(t => t.Status == (int)EmCellStatus.Normal && t.BusinessType == 0 && t.IsLock == false && t.FullStatus == 0 && t.LogicalPartCode == logicalPartCode && enabledShelves.Contains(t.ShelfId)).Select(t => t.RoutewayId).Distinct().ToList(); //只取巷道id
                        //if (routewayIds == null || routewayIds.Count == 0)
                        //{
                        //    logicalPartCode = commonlogicalPartType == null ? "" : commonlogicalPartType.ItemCode;
                        //    routewayIds = cellQuery.Where(t => t.Status == (int)EmCellStatus.Normal && t.BusinessType == 0 && t.IsLock == false && t.FullStatus == 0 && t.LogicalPartCode == logicalPartCode && enabledShelves.Contains(t.ShelfId)).Select(t => t.RoutewayId).Distinct().ToList();
                        //}
                        //if (routewayIds != null && routewayIds.Count > 0)
                        //{

                        //}
                    }


                    hasCell = true;


                    //找到此巷道同种物料同批次的，且浅位无货深位有货的
                    var depthCellQuery = (from cell in cellQuery
                                          join inv in inventoryQuery
                                          on cell.Id equals inv.LocationId
                                          where cell.Status == (int)EmCellStatus.Normal
                                          && cell.IsLock == false && inv.Status == 1
                                          && cell.BusinessType == 0
                                          select cell
                                         );
                    var depthLockCellQuery = (from cell in cellQuery
                                              join inv in inventoryQuery
                                              on cell.Id equals inv.LocationId
                                              where (cell.Status != (int)EmCellStatus.Normal
                                              || cell.IsLock == true || inv.Status != 1)
                                              select cell
                                        );
                    var celllist = cellQuery.Where(t => t.Status == (int)EmCellStatus.Normal && t.FullStatus == 0 && t.IsLock == false && t.BusinessType == 0
                           && depthCellQuery.Where(dc => dc.LayerNo == t.LayerNo && dc.LineNo == t.LineNo && dc.ColumnNo == t.ColumnNo).Any()
                           && !depthLockCellQuery.Where(dc => dc.LayerNo == t.LayerNo && dc.LineNo == t.LineNo && dc.ColumnNo == t.ColumnNo).Any()).ToList();
                    if (!string.IsNullOrEmpty(logicalPartCode))
                    {
                        celllist = celllist.Where(t => t.LogicalPartCode == logicalPartCode).ToList();
                    }
                    //优先找同种物料、距离最短、深度最深的货位
                    allotCell = celllist.OrderBy(c => c.LineNo)
                        .ThenBy(c => c.DistanceValue)
                        .ThenBy(c => c.LayerNo)
                        .ThenBy(c => c.ColumnNo)
                        .FirstOrDefault();
                    if (allotCell == null)//如果没有找到匹配
                    {
                        int i = 0;
                        string key = "_routeway";
                        int count = 0;
                        do
                        {
                            var cells = cellQuery.Where(t => t.Status == (int)EmCellStatus.Normal && t.FullStatus == 0 && t.IsLock == false && t.BusinessType == 0).ToList();
                            if (!string.IsNullOrEmpty(logicalPartCode))
                            {
                                cells = cells.Where(t => t.LogicalPartCode == logicalPartCode).ToList();
                            }
                            //优先找距离最短、深度最深的货位

                            allotCell = cells.OrderBy(c => c.LineNo)
                        .ThenBy(c => c.DistanceValue)
                        .ThenBy(c => c.LayerNo)
                        .ThenBy(c => c.ColumnNo)
                        .FirstOrDefault();
                            #region 注释掉的
                            //if (allotCell != null)
                            //{
                            ////当分配了一个双深位浅位仓位时，需要判断深位是否是同种物料批次，此处是为了校验，正常不会进入该条件。先保留
                            //if (allotCell.DepthIndex == 0 && allotCell.IsMaxDepth == false)
                            //{
                            //    //CellModel depthCell = cellService.GetCell(context, new CellCriteriaModel { IsMaxDepth = true, DepthIndex = 1, LineNO = cellList[0].LineNO, LayerNO = cellList[0].LayerNO, ColumnNO = cellList[0].ColumnNO });
                            //    CellModel depthCell = cellQuery.Where(t => t.IsMaxDepth == true && t.DepthIndex == 1 && t.LineNO == allotCell.LineNO && t.LayerNO == allotCell.LayerNO && t.ColumnNO == allotCell.ColumnNO).FirstOrDefault();
                            //    if (depthCell.Status == EmCellStatus.Normal)
                            //    {
                            //        //深位如果有货
                            //        if (depthCell.FullStatus == 0)
                            //        {
                            //            errorMsg = "仓位分配逻辑有误或数据有误";
                            //            return false;
                            //        }
                            //        InventoryModel inventory = context.Query<InventoryModel>().Where(t => t.LocationId == depthCell.Id).FirstOrDefault();
                            //        if (inventory == null)
                            //        {
                            //            errorMsg = "库存数据有误";
                            //            return false;
                            //        }
                            //        if (inventory.MaterialId != materialId || inventory.MaterialKeyId != materialKeyId||inventory.QualityState!= qualityState)
                            //        {
                            //            errorMsg = "库存数据有误";
                            //            return false;
                            //        }
                            //    }
                            //}
                            //}
                            #endregion
                            if (allotCell != null)
                            {
                                break;
                            }
                            i++;

                        } while (i < count);
                    }
                    if (hasCell && allotCell == null)
                    {
                        int sameMaterialCount = 0;

                        if (!string.IsNullOrEmpty(logicalPartCode))
                        {
                            var sameMaterial = (from cell in cellQuery
                                                join inv in inventoryQuery
                                                on cell.Id equals inv.LocationId
                                                where cell.LogicalPartCode == logicalPartCode
                                                && cellQuery.Where(ct => ct.LayerNo == cell.LayerNo
                                                && ct.LineNo == cell.LineNo
                                                && ct.ColumnNo == cell.ColumnNo
                                                && ct.Status == (int)EmCellStatus.Normal
                                                && ct.IsLock == false && ct.BusinessType == 0
                                                && ct.FullStatus == 0).Any()
                                                && cell.IsLock == false && inv.Status == 1
                                                && cell.BusinessType == 0
                                                select cell
                                      ).ToList();
                            sameMaterialCount = sameMaterial.Count();
                        }
                        else
                        {
                            var sameMaterial = (from cell in cellQuery
                                                join inv in inventoryQuery
                                                on cell.Id equals inv.LocationId
                                                where cellQuery.Where(ct => ct.LayerNo == cell.LayerNo
                                                && ct.LineNo == cell.LineNo
                                                && ct.ColumnNo == cell.ColumnNo
                                                && ct.Status == (int)EmCellStatus.Normal
                                                && ct.IsLock == false && ct.BusinessType == 0
                                                && ct.FullStatus == 0).Any()
                                                && cell.IsLock == false && inv.Status == 1
                                                && cell.BusinessType == 0
                                                select cell
                                     ).ToList();
                            sameMaterialCount = sameMaterial.Count();
                        }
                        waitIndex++;
                        if (waitIndex > 20)//最多等待10分钟
                        {
                            break;
                        }
                        hasCell = sameMaterialCount > 0;
                        if (sameMaterialCount > 0)
                        {
                            Thread.Sleep(30000);
                        }
                    }
                    else
                    {
                        if (!hasCell)
                        {
                            errorMsg = "没有仓位可分配";
                        }
                    }
                } while (hasCell && allotCell == null);//没有分配到仓位，同时又有仓位时，则说明深位还未完成，需等待

                return allotCell;
            }
            catch (Exception ex)
            {
                errorMsg = "未知异常:" + ex.Message;
                return null;
            }
        }


        public bool TCellAdd(int whId, int shelfId, int storey, int arrange, out int count,out string message)
        {
            message = "";
            count = 0;
            var whList = Context.TWarehouses.Where(x => x.Id == whId).ToList();
            if (whList.Count <= 0)
            {
                message = "暂无库房";
                return false;
            }
            var shelfList = Context.TShelves.Where(x => x.Id == shelfId).ToList();
            if(shelfList.Count <= 0)
            {
                message = "暂无货架";
                return false;
            }

            for (int b = 1; b <= arrange; b++)
            {
                for (int c = 1; c <= storey; c++)
                {
                    TCell cell = new TCell();
                    string formattedNumber = $"cell:{whId:00}_{shelfList.FirstOrDefault().Number:00}_{b:00}_{c:00}";
                    cell.Code = formattedNumber;
                    string name = $"{whList.FirstOrDefault().Name}{shelfList.FirstOrDefault().Name}{b}层{c}位";
                    cell.Name = name;
                    cell.CellType = 1;
                    cell.WhId = whList.FirstOrDefault().Id;
                    cell.WhCode = whList.FirstOrDefault().Code;
                    cell.WhName = whList.FirstOrDefault().Name;
                    cell.ShelfName = shelfList.FirstOrDefault().Name;
                    cell.ShelfId = shelfId;
                    cell.ShelfCode = shelfList.FirstOrDefault().Code;
                    cell.Status = 1;
                    cell.LineNo = shelfId;
                    cell.ColumnNo = b;
                    cell.LayerNo = c;
                    cell.DepthIndex = 1;
                    cell.BusinessType = 0;
                    cell.IsLock = false;
                    cell.CreateDate = DateTime.Now;
                    cell.CreateUserId = 37;
                    cell.CreateUserName = "管理员";
                    cell.FullStatus = 0;
                    cell.IsMaxDepth = false;
                    Context.TCells.Add(cell);
                    count++;
                    if (Context.SaveChanges() <= 0)
                    {
                        return false;
                    }


                }
            }
            return true;
        }

        public bool AddPriceCellForSqlite(List<TPriceTags> list)
        {
            using var tran = Context.Database.BeginTransaction();
            try
            {
                //创建表（如果不存在）
                bool aa = sqlite.Database.EnsureCreated();
                // 设置连接字符串
                string connectionString = "Data Source=/root/WMS/PC-Service/wwwroot/file/chat.db";

                // 创建连接对象
                using (var connection = new SqliteConnection(connectionString))
                {
                    // 打开连接
                    connection.Open();

                    // 创建SQL命令对象
                    using (var command = connection.CreateCommand())
                    {
                        // 设置清空缓存的SQL语句
                        command.CommandText = "PRAGMA cache_size=0;";

                        // 执行SQL命令
                        command.ExecuteNonQuery();

                        Console.WriteLine("Cache cleared.");
                    }

                    // 关闭连接
                    connection.Close();
                }
                var priceTagsRemove = sqlite.PriceTagsTables.AsQueryable().ToList();
                sqlite.PriceTagsTables.RemoveRange(priceTagsRemove);
                foreach (var item in list)
                {

                    PriceTagsTable priceTagsTable = new PriceTagsTable()
                    {
                        PriceTagsUrl = item.PriceTagsUrl,
                        CellCode = item.CellCode,
                        Sign = item.Sign,
                        Store_code = item.Store_code
                    };
                    sqlite.PriceTagsTables.Add(priceTagsTable);
                }
                if (sqlite.SaveChanges() <= 0)
                {
                    tran.Rollback();
                    return false;
                }
                tran.Commit();
                return true;
            }
            catch
            {
                tran.Rollback();
                return false;
            }
        }
    }
}